package day15;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class Test07 {
    public static void main(String[] args) {
        // 目录
        String dirPath = "day15";
        // 文件名
        String filName = "image.png";
        // 复制的份数
        int number = 10;
        // 创建对象
        File dir = new File(dirPath);
        File img = new File(dir,filName);
        // 创建输入流对象
        InputStream iS = null;
        // 创建输出流对象
        OutputStream[] outputStreams = new OutputStream[number];
        // try-catch 捕获异常
        try {
            iS = new FileInputStream(img);
            for(int i = 0;i < outputStreams.length;i++){
                String[] filNames = filName.split("\\.");
                String name = filNames[0];
                String suffix = filNames[1];
                String newFileName = name + "_copy"+(i+1)+"."+suffix;
                OutputStream oS = new FileOutputStream(newFileName);
                // 输出流对象保存到数组中
                outputStreams[i] = oS;
            }
            //开始复制
            byte[] buf = new byte[1024];
            // 定义变量记录读到的字节数
            int len;
            while ((len = iS.read(buf)) != -1) {
                for (OutputStream os : outputStreams) {
                    os.write(buf,0,len);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            // 关闭输出流
            for (OutputStream os : outputStreams) {
                if(os != null){
                    try {
                        os.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            // 关闭输入流
            if(iS != null){
                try {
                    iS.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            
        }
    }
}
